/* Terraform - (C) 1997-2002 Robert Gasch (r.gasch@chello.nl)
 *  - http://terraform.sourceforge.net
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */


/*
 * Initial main.c file generated by Glade. Edit as required.
 * Glade will not overwrite this file.
 */

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#ifdef ENABLE_NLS
#  include <locale.h>
#  include <libintl.h>
#endif

#include <gnome.h>
#include <libgnomeui/gnome-window-icon.h>
#include <libxml/parser.h>

#include "callbacks.h"
#include "filenameops.h"
#include "genrandom.h"
#include "installer.h"
#include "interface.h"
#include "mainwindow.h"
#include "reader.h"
#include "support.h"
#include "support2.h"
#include "tterrain.h"
#include "terrainwindow.h"


static void register_terrain (TTerrain  *terrain,
                              GtkWidget *main_window,
                              gchar     *source);
static void error_msg        (gchar     *msg);


int
main (int argc, char *argv[])
{
  GnomeProgram      *terraform_program;
  gchar             *load_error = NULL;
  gboolean           is_installed;
  TTerrain          *terrain;
  GtkWidget         *main_window;
  MainState         *main_state;
  poptContext        poptCtx = NULL;

  int                param_do_chooser = 0;
  int                param_do_install = 0;
  char              *param_factor = NULL;
  int                param_generate_terrain = 0;
  char              *param_gamma = NULL;
  int                param_size = 0;
  int                param_gen_type = -1;
  int                param_max_undo = 0;

  struct poptOption  options[] = 
    {
      {"chooser", 'c', POPT_ARG_NONE, &param_do_chooser, 0,
       N_("Run terrain chooser upon startup"), 
       N_("type bitmap")},
      {"factor", 'f', POPT_ARG_STRING, &param_factor, 0,
       N_("Set scaling factor for random generation"),
       N_("factor")},
      {"gamma", 'm', POPT_ARG_STRING, &param_gamma, 0,
       N_("Set gamma factor"),
       N_("gamma_factor")},
      {"generate", 'g', POPT_ARG_NONE, &param_generate_terrain, 0,
       N_("Generate random terrain upon startup"),
       N_("size")},
      {"install", 'i', POPT_ARG_NONE, &param_do_install, 0,
       N_("Installs Terraform files in home directory"),
       N_("install")},
      {"size", 's', POPT_ARG_INT, &param_size, 0,
       N_("Set the default terrain size"),
       N_("size")},
      {"type", 't', POPT_ARG_INT, &param_gen_type, 0,
       N_("Set terrain types for random generation"), 
       N_("type_bitmap")},
      {"undo", 'u', POPT_ARG_INT, &param_max_undo, 0,
       N_("Set the maximum size of the undo queue"), 
       N_("max_undo")},

      {(char *) NULL, '\0', 0, NULL, 0}
    };

  /* Initialize libxml2 */
  xmlKeepBlanksDefault (0);

#ifdef ENABLE_NLS
  bindtextdomain (GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR);
  bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
  textdomain (GETTEXT_PACKAGE);
#endif

  terraform_program =
    gnome_program_init (PACKAGE, VERSION, LIBGNOMEUI_MODULE,
                        argc, argv,
                        GNOME_PARAM_APP_DATADIR, TERRAFORM_DATA_DIR,
                        GNOME_PARAM_POPT_TABLE, options,
                        GNOME_PARAM_NONE);

  gtk_widget_set_default_colormap (gdk_rgb_get_cmap ());
  gtk_widget_set_default_visual (gdk_rgb_get_visual ());

  gnome_window_icon_init ();
  gnome_window_icon_set_default_from_file (GNOME_DATA_DIR "/pixmaps/terraform.png");
  /* Tearoff menus are buggy */
  /* gnome_preferences_set_menus_have_tearoff (FALSE); */

  gtk_init (&argc, &argv);
  is_installed = tf_install_verify ();
  if (param_do_install || !is_installed)
    {
      //FIXME: check for home directory
      tf_user_install ();

      /* --install ignores all other command line params and exits. 
       * autoinstall ignores other commane line params but launches 
       * program after install 
       */
      if (!param_do_install && is_installed == 1)
        {
        main_window = create_main_window ();
        main_window_initialize (main_window);
        gtk_widget_show (main_window);
        }
    }
  else  
    {
      /* normal command line processing */
      main_window = create_main_window ();
      main_window_initialize (main_window);
      gtk_widget_show (main_window);

      main_state = gtk_object_get_data (GTK_OBJECT (main_window), "data_state");

      /* --factor */
      if (param_factor != NULL)
        {
	  double factor = strtod(param_factor, NULL); 

	  if (factor <= 0)
            error_msg (_("--factor command line option: Factor must be greater than 0"));
          else
          if (factor >= 1)
            error_msg (_("--factor command line option: Factor must be smaller than 1"));
          else
            main_state->genfactor = factor;
        }

      /* --gamma */
      if (param_gamma != NULL)
        {
          double gamma = strtod(param_gamma, NULL); 

          if (gamma <= 0)
            error_msg (_("--gamma command line option: Gamma must be greater than 0"));
          else
          if (gamma > 5)
            error_msg (_("--gamma command line option: Gamma can not be more than 5"));
          else
            main_state->gamma = gamma;
        }

      /* --size */
      if (param_size != 0)
        {
          if (param_size < 10)
            error_msg (_("--size command line option: Size must be at least 10"));
          else
          if (param_size > 16384) /* == 268435456 locations == +- 1 GB RAM */
            error_msg (_("--size command line option: Size can not be more than 16384"));
          else
            main_state->default_size = param_size;
        }
      else
        {
          param_size = main_state->default_size;
        }

      /* --type */
      if (param_gen_type != -1)
        {
          if (param_gen_type > GEN_TYPE_ALL)
            error_msg (g_strdup_printf (_("--type command line option: Type must be less than %d"), GEN_TYPE_ALL));
          else
          if (param_gen_type < 0)
            error_msg (_("--type command line option: Type must be at least 0"));
          else
            main_state->gentypes = param_gen_type;
        }

      /* --undo */
      if (param_max_undo != 0)
        {
        if (param_max_undo < 1)
          error_msg (_("--undo command line option: must be at least 1"));
        else
        if (param_max_undo > 50)
          error_msg (_("--undo command line option: can not be more than 50"));
        else
          main_state->max_undo = param_max_undo;
        }

      /* --chooser */
      if (param_do_chooser)
        {
          GtkWidget *chooser;
          GtkWidget *randomize;

          chooser = create_chooser_window ();
          gtk_object_set_data (GTK_OBJECT (chooser), "data_parent", main_window);
          gtk_widget_show (chooser);

          randomize = lookup_widget (chooser, "randomize");
          on_randomize_clicked (GTK_BUTTON (randomize), &param_gen_type);
        }

      /* --generate */
      if (param_generate_terrain)
        {
          terrain = t_terrain_generate_random (param_size, main_state->genfactor, main_state->gentypes);
          register_terrain (terrain, main_window, _("Generate Random"));
        }

      while (poptPeekArg (poptCtx))
        {
          const char *filename;

          filename = poptGetArg (poptCtx);

          terrain = t_terrain_load (filename, FILE_AUTO);
          if (terrain == NULL)
            {
              if (load_error == NULL)
                load_error = g_strdup_printf (_("Could not load the file:\n%s"), filename);
              else
                {
                  gchar *temp;

                  temp = g_strdup_printf ("%s %s", load_error, filename);
                  g_free (load_error);
                  load_error = temp;
                }
            }
          else
            register_terrain (terrain, main_window, _("Load"));
        }

      if (load_error != NULL)
        {
          error_msg (load_error);
          g_free (load_error);
          load_error = NULL;
        }
    }

  gtk_main ();
  return 0;
}


static void
error_msg (gchar *msg)
{
  GtkWidget *error_dialog;

  error_dialog = gnome_error_dialog (msg);

  gtk_widget_show (error_dialog);
}


static void
register_terrain (TTerrain  *terrain,
                  GtkWidget *main_window,
                  gchar     *source)
{
  GtkWidget *terrain_window;
     
  t_terrain_ref (terrain);
  terrain_window = terrain_window_new (main_window, terrain);
  terrain_window_save_state (terrain_window, source);
  t_terrain_unref (terrain);
}
